﻿
template<typename T>
Link<T>::Link()
{
    count = 0;
    phead = new Node<T>();
    phead->next=nullptr;
}

template<typename T>
Link<T>::~Link()
{
    Link<T>::pointer pNode=phead->next;
    for(int i=1; i<=count; i++)
    {
        Link<T>::pointer temp=pNode;
        pNode=pNode->next;
        delete temp;
    }
    count=0;
}

template<typename T>
int Link<T>::size()
{
    return count;
}

template<typename T>
bool Link<T>::isEmpty()
{
    if(count==0)
        return false;
    else return true;
}

template<typename T>
Node<T>* Link<T>::insert(int index, T t)
{
    Link<T>::pointer preNode = getNode(index);
    if(preNode){
        Link<T>::pointer newNode = new Node<T>(t,preNode->next);
        //    newNode->next=preNode->next;
        preNode->next=newNode;
        count++;
        return newNode;
    }
    return nullptr;
}

template<typename T>
Node<T>* Link<T>::insert_head(T t)
{
    insert(0,t);
}

template<typename T>
Node<T>* Link<T>::insert_last(T t)
{
    insert(count,t);
}

template<typename T>
Node<T>* Link<T>::del(int index)
{
    if(index>0&&index<=count){
        Link<T>::pointer node = getNode(index);

        Link<T>::pointer preNode=getNode(index-1);
        preNode->next=node->next;
        count--;
        delete node;
        return preNode->next;
    }
    else
        return nullptr;

}

template<typename T>
Node<T>* Link<T>::del_head()
{
    return del(1);
}

template<typename T>
Node<T>* Link<T>::del_last()
{
    return del(count);
}

template<typename T>
T Link<T>::get(int index)
{
    Link<T>::pointer node=getNode(index);
    return node->value;
}

template<typename T>
T Link<T>::get_head()
{
    return getNode(1)->value;
}

template<typename T>
T Link<T>::get_last()
{
    return getNode(count)->value;
}

template<typename T>
Node<T>* Link<T>::getHead()
{
    return phead->next;
}

template<typename T>
Node<T>*  Link<T>::getNode(int index)
{
    Link<T>::pointer nextNode;

    if(index==0)
        return phead;

    nextNode = phead->next;
    for(int i=1; i<index; i++)
    {
        if(nextNode)
            nextNode=nextNode->next;
        else
            break;
    }
    return nextNode;
}
